/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Home-pc
 * Date: 2023-09-23
 * Time: 16:50
 */
class MyBlockingQueue{
    //使用循环队列来表示这个阻塞队列
    private String[] items=new String[10];
    //队列的头部
    volatile int head=0;
    //tail:队列的尾部的下一个元素. 总的来说, 队列中有效元素的范围 [head, tail)
    // 当 head 和 tail 相等(重合), 相当于空的队列.
    volatile int tail=0;
    //size表示队列当前的元素个数
    volatile int size=0;

    public void put(String elem) throws InterruptedException {
        synchronized (this){
            while(size>=items.length){//队列满
                //return;
                this.wait();
            }
            items[tail]=elem;
            tail++;
            if(tail>= items.length){
                tail=0;
            }
            size++;
            this.notify();
        }
    }
    public String take() throws InterruptedException {
        synchronized (this){
            while(size==0){
               // return null;
                this.wait();
            }
            String elem=items[head];
            head++;
            if(head>= items.length){
                head=0;
            }
            size--;
            this.notify();
            return elem;
        }
    }
}
public class Demo19 {
    public static void main(String[] args) {
/*    MyBlockingQueue queue=new MyBlockingQueue();
    queue.put("aaa");
    queue.put("bbb");
    queue.put("ccc");
    queue.put("ddd");

    String elem= queue.take();
    System.out.println("elem="+elem);
    elem= queue.take();
    System.out.println("elem="+elem);
    elem= queue.take();
    System.out.println("elem="+elem);*/
        //创建两个线程，表示生产者和消费者
        MyBlockingQueue queue=new MyBlockingQueue();
        Thread t1=new Thread(() ->{
            int count=0;
           while (true){
               try {
                   queue.put(count + "");
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               System.out.println("生产"+count);
               count++;
               try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        });
        Thread t2=new Thread(() ->{
            while (true){
                String elem= null;
                try {
                    elem = queue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("消耗"+elem);
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
    }
}
